<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if(!class_exists('CI_Model')) { class CI_Model extends Model {} }

class Polls_model extends CI_Model {
	var $perpage = 10;
	var $url;
	public function __construct() {
	   parent::__construct();
	   $this->url = $this->uri->segment(1);
	}
	public function index() {
		$data['polls'] = $polls = $this->db->select()->from('polls')->order_by('poll_id', 'desc')->get()->result_array();
		$data['url'] = $this->url;
		$out['text'] = $this->load->view('modules/polls/index', $data, true);
		return $out;
	}
	public function block() {
		$data['polls'] = $polls = $this->db->select()->from('polls')->order_by('poll_id', 'desc')->limit(2)->get()->result_array();
		return $this->load->view('modules/polls/block', $data, true);
	}
	public function show($args) {
		$p_data = $this->input->post();
		$id = $args[0];
		$page = $this->db->select()->from('polls')->where('poll_id', $id)->get()->row_array();
		$answer = $this->db->select()->from('answers')->where('answer_id', $p_data['answer'])->get()->row_array();
		$answered = $this->db->select()->from('polls_results')->where('result_poll', $id)->where('result_user', $this->session->userdata('session_id'))->get()->result_array();
		if (sizeof($page) <= 0 || sizeof($answer) <= 0 || sizeof($answered) > 0) redirect('/');
		$count_1 = $answer['answer_count'] + 1;
		$this->db->where('answer_id', $p_data['answer'])->update('answers', array('answer_count' => $count_1));
		$count_2 = $page['poll_count'] + 1;
		$this->db->where('poll_id', $id)->update('polls', array('poll_count' => $count_2));
		$ans['result_id'] = 0;
		$ans['result_poll'] = $id;
		$ans['result_user'] = $this->session->userdata('session_id');
		$this->db->insert('polls_results', $ans);
		$this->session->set_flashdata('msg', 'Спасибо, Ваш голос учтен!');
		redirect($this->url);
		exit();
	}
}